package com.peans.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("${server.error.path}")
public class TestErrorController implements ErrorController{

	@Autowired
	private ErrorAttributes errorAttributes;
	
	@Value("${server.error.path}")
	private  String path;
	
	@RequestMapping(produces = "text/html")
	public ModelAndView errorHtml(HttpServletRequest request,
			HttpServletResponse response) {
		HttpStatus status = getStatus(request);
		RequestAttributes requestAttributes = new ServletRequestAttributes(request);
		Map<String, Object> model = errorAttributes.getErrorAttributes(requestAttributes, true);
		if (status.is4xxClientError()) {
			return new ModelAndView("notfound.html", model);
		}
		if (status.is5xxServerError()) {
			return new ModelAndView("serverError.html", model);
		}
		return new ModelAndView("serverError.html", model);
	}

	@Override
	public String getErrorPath() {
		return path;
	}

	protected HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request
				.getAttribute("javax.servlet.error.status_code");
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		try {
			return HttpStatus.valueOf(statusCode);
		}
		catch (Exception ex) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
	}
	
	
}
